<?php

class PayController extends \BaseController {

    public function test(){
        $customer_id = Session::get('customer_id');
        echo $customer_id;
    }
    public function order(){
        $customer_id = Session::get('customer_id');
        $customer = Customer::find($customer_id);

        $pub = Pub::find(1);
//        if (Cache::has('token'))
//        {
//            //
//            $value = Cache::get('token');
//        }else{
//            $value =  Wechat::get_access_token($pub->AppID,$pub->AppSecret);
//            Cache::put('token', $value, 240);
//        }



        $appid = $pub->AppID;
        $appsecret = $pub->AppSecret;

        $id = Input::get('id');

        $mount = Mount::find($id);

        $machinepr = Machinepr::where('machine_id',$mount->machine_id)->where('area_id',$customer->city)->first();

        $total = $machinepr->price*100;
        $total = (int)$total;
        $customer_id = Session::get('customer_id');
        $filterins = Filterin::whereHas('mount', function($q)
        {
            $customer_id = Session::get('customer_id');
            $q->where('customer_id', $customer_id)->where('state','>',1);

        })->get();
        $name = array('filterone','filtertwo','filterthree','filterfour','filterfive','filtersix','filterseven','filtereight','filternine','filterten');
        for($i = 0;$i < $mount->machine->count ;$i++){
            $filters[] = $name[$i];
        }

        $filtercos = Filterco::where('customer_id',$customer_id)->get();
        $body = $mount->machine->name;

//获取code
//        $code = isset($_GET['code'])?$_GET['code']:'no code';
////echo 'code: [',$code,']<br />';
//
////获取code后，请求以下链接获取access_token：
//        $acc = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
//        $res = json_decode(https_request($acc),true);
//        $access_token = $res['access_token'];
        $openid = $customer->openid;
//echo $access_token , '<br />';
//echo $openid , '<br />';




        $time = $this->build_order_no(); //拼接appid + 时间
        $xml = '<xml>
  <openid><![CDATA['.$openid.']]></openid>
  <body><![CDATA['.$body.']]></body>
  <out_trade_no><![CDATA['.$time.']]></out_trade_no>
  <total_fee>'.$total.'</total_fee>
  <notify_url><![CDATA[http://crm.leaderphos.com/pay/notify/]]></notify_url>
  <trade_type><![CDATA[JSAPI]]></trade_type>
  <appid><![CDATA['.$appid.']]></appid>
  <mch_id>1226760102</mch_id>
  <spbill_create_ip><![CDATA['.$_SERVER['REMOTE_ADDR'].']]></spbill_create_ip>
  <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>
</xml>';
        $arr = $this->xmlToArray($xml); //转成数组
        $str = $this->formatBizQueryParaMap($arr,false); //字典序排序 1
        $stringSignTemp = $str.'&key='.$pub->apiKey;  //把key拼接上 2
        $md5 = md5($stringSignTemp); //md5 3
        $sign = strtoupper($md5); //再转大写 获取sign 4
//echo 'sign: ',$sign ,'<br />';



//提交xml到指定的url上
        $x = '<xml>
  <openid><![CDATA['.$openid.']]></openid>
  <body><![CDATA['.$body.']]></body>
  <out_trade_no><![CDATA['.$time.']]></out_trade_no>
  <total_fee>'.$total.'</total_fee>
  <notify_url><![CDATA[http://crm.leaderphos.com/pay/notify/]]></notify_url>
  <trade_type><![CDATA[JSAPI]]></trade_type>
  <appid><![CDATA['.$appid.']]></appid>
  <mch_id>1226760102</mch_id>
  <spbill_create_ip><![CDATA['.$_SERVER['REMOTE_ADDR'].']]></spbill_create_ip>
  <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>
  <sign><![CDATA['.$sign.']]></sign>
</xml>';
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';  //把xml数据提交到这个url上
        $res = $this->xmlToArray($this->postXmlCurl($x,$url));  //返回结果为xml格式 再转成数组
        $prepay_id = ($res['prepay_id']); //得到了 prepay_id
//echo $prepay_id;



        $jsApiParameters = $this->getParameters($appid,$prepay_id,$pub->apiKey);

//        echo $jsApiParameters;

        return View::make('pay.test',compact('jsApiParameters','mount','filterins','filtercos','type','filters','time'));
    }


    public function notify(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);


        if($postObj->result_code == 'SUCCESS') {
            $service = Service::where('service_num',$postObj->out_trade_no)->first();
            if ($service->all == 1) {
                echo 'success';
            } else {
                $service->all = 1;
                $service->total_fee = $postObj->total_fee;
                $service->pay_time = time();
                $service->save();
            }
        }
    }
    public function buy_notify(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);


        if($postObj->result_code == 'SUCCESS') {
            $buyrecord = Buyrecord::where('out_trade_no',$postObj->out_trade_no)->first();
            if ($buyrecord->state == 2) {
                echo 'success';
            } else {
                $buyrecord->state = 2;
                $buyrecord->total_fee = $postObj->total_fee;
                $buyrecord->pay_time = time();
                $buyrecord->save();
            }
        }
    }

    public function pay_return(){
        $id = Input::get('id');
        $num = Input::get('num');
        if((int)$id == 0 || $num == ''){
            echo "出错了，请返回菜单重试";
            exit;
        }
        $customer_id = Session::get('customer_id');


        DB::beginTransaction();//开启事务

        $mount = Mount::find($id);
        if($customer_id != $mount->customer_id){
            echo "出错了，请返回菜单重试";
            exit;
        }
        $service = new Service();
        $service->paytype = 2;
        $service->all = 0;
        $service->section_id =  $mount->section_id;
        $service->type =  10;
        $service->mount_id =  $id;
        $service->service_num =  $num;
        $service->customer_id =  $customer_id;
        $service->state =  1;
        $service->save();

        $count = Work::where('section_id',$mount->section_id)->where('paidan',1)->count();
        if($count != 0){
            $work = Work::where('section_id',$mount->section_id)->where('paidan',1)->first();
            $mount = Mount::find($id);
            $this->forworker($work->openid,$service,$mount);
        }
        $mount->state = 2;
        $mount->save();

        DB::commit();//提交事务

        return Redirect::route('services.index');
    }


    public function forworker($openid,$service,$mount){

        $data[0] = '您有一条新工单等待派单';

        $type[1] = '试用';
        $type[10] = '订购';
        $type[11] = '拆机';
        $type[12] = '维修';
        $type[13] = '换芯';


        $data[1] = $mount->mount_name;
        $data[2] = $mount->mount_mobile;
        $data[3]=  $type[$service->type];
        $data[4]=  $service->remark;
        $data[5]=  '无';
        $data[6]=  '点击安排派单';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=paidan_'.$service->id.'#wechat_redirect';

        \Template::newone($openid,$data,$url,3);
    }

    /**
     *  作用：产生随机字符串，不长于32位
     */
    function createNoncestr( $length = 32 ){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    /**
     *  作用：设置jsapi的参数
     */
    function getParameters($appid,$prepay_id,$apiKey)
    {
        $jsApiObj["appId"] = $appid;
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=$prepay_id";
        $jsApiObj["signType"] = "MD5";

        //把上面的参数字典序排序
        $one = $this->formatBizQueryParaMap($jsApiObj,false);
        $two = $one.'&key='.$apiKey;
        $three = md5($two);
        $four= strtoupper($three);

        $jsApiObj["paySign"] = $four;
        $parameters = json_encode($jsApiObj);

        return $parameters;
    }

    //http 请求
    function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     *  作用：以post方式提交xml到对应的接口url
     */
    function postXmlCurl($xml,$url,$second=30){
        //初始化curl
        $ch = curl_init();
        //设置超时
        //curl_setopt($ch, CURLOP_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);
        //返回结果
        if($data){
            //curl_close($ch);
            return $data;
        }else{
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }


    /**
     *  作用：将xml转为array
     */
    function xmlToArray($xml){
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }


    /**
     *  作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode){
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v){
            if($urlencode){
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }

    /**
     *
     * uniqid - 官方是这样说的：
     * Gets a prefixed unique identifier based on the current time in microseconds.
     */
    function build_order_no()
    {
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }


}